package com.example.selfservicestation.mob

import android.content.Context
import androidx.annotation.WorkerThread
import com.example.selfservicestation.extensions.isAlive
import com.example.selfservicestation.util.Executor
import com.example.selfservicestation.util.Logger
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.math.BigInteger
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.math.ceil


/**
 * ModBus 主控板控制器
 */
object ModBusController {
    private const val TAG = "ModBus_Ctrl"

    private const val LISTENER_TYPE_WEIGHT = 2
    private const val LISTENER_TYPE_STATUS = 3
    private const val LISTENER_TYPE_TEMPERA = 4

    // 主控板管理器
    var modBusManager: ModBusManager? = null
    private var slaveCount: Int = 1

    private val threadPool = Executors.newScheduledThreadPool(4)

    private val listeners = ArrayList<StatusListener>()

    private val fullPercentListeners = ArrayList<FullPercentListener>()

    // 是否中断读取桶状态
    private var pauseReadTrashBin: ArrayList<Boolean> = ArrayList()

    var shouldStopUpgrade = false

    fun setSlaveCount(count: Int) {
        modBusManager?.slaveCount = count
        slaveCount = count
    }

    data class FullPercent(val percent: Int, val checkByLaser: Boolean)

    class FullPercentListener(
        val key: Any,
        val listener: (List<FullPercent>) -> Unit
    )

    class StatusListener(
        val key: Any,
        val listener: (List<Int>) -> Unit,
        val type: Int
    )

    fun interruptReadTrashBinStatus(interrupt: Boolean) {
        pauseReadTrashBin.clear()
        pauseReadTrashBin.add(interrupt)
    }

    fun start(ctx: Context) {
        Logger.i(TAG, "start()")
        modBusManager?.stop()
        PortManager.openCtrlBord(ctx)
            ?.let { pm ->
                return@let ModBusManager(
                    slaveCount, pm, true
                )
            }
            ?.also {
                modBusManager = it
            }
            ?.start()
    }



    /**
     * 回调的重量单位：0.01kg、10g
     */
    fun registerWeightListener(key: Any, listener: (List<Int>) -> Unit) {
        listeners.add(StatusListener(key, listener, LISTENER_TYPE_WEIGHT))
    }

    fun registerStatusListener(key: Any, listener: (List<Int>) -> Unit) {
        listeners.add(StatusListener(key, listener, LISTENER_TYPE_STATUS))
    }

    fun registerTemperaListener(key: Any, listener: (List<Int>) -> Unit) {
        listeners.add(StatusListener(key, listener, LISTENER_TYPE_TEMPERA))
    }

    fun unregisterListener(key: Any) {
        val it = listeners.iterator()
        while (it.hasNext()) {
            if (it.next().key == key) {
                it.remove()
            }
        }
    }



    fun stop() {
        Logger.i(TAG, "stop()")
        modBusManager?.stop()
        modBusManager = null
    }

}